<template>
  <div style="background-color: #f4f6f8; width: 100vw; min-height: 100vh; height: auto;">
    <header style="height: 60px; width: 100vw;
     background-color:#ffff; display: flex; align-items: center; justify-content: space-between;" >
        <el-page-header @back="$router.back()"
        :content="$route.params.id ? '编辑角色' : '添加角色'"
        style="padding: 20px; "
        >
        <template #content>
        </template>
        </el-page-header>
          <div>
        <el-text style="font-size: 18px; font-weight: 500;margin-right: 20px; ">管理员</el-text>
      </div>
    </header>
    <main style="padding: 20px;"> 
      <!-- 步骤条 -->
       <div style="display: flex; ">
         <div style=" height: 250px; width: 400px; margin-top: 20px; ">
            <el-steps direction="vertical" :active="activeStep"  :space="60">
            <el-step title="角色信息"  class="custom-step">
                <template #icon>
                    <div :style="{width: '15px',  height: '15px',
                    borderRadius: '8px',  
                    position: 'relative',
                    backgroundColor: activeStep >= 0 ? '#408dff' : '#d7d9da'
                    }">
                    <div style="width: 10px; height: 10px; background-color: #fff;
                    border-radius: 5px; position: absolute; top: 2.5px; left: 2.55px;"></div>    
                </div>
                </template>
            </el-step>
              <el-step title="权限信息" class="custom-step">
                 <template #icon>
                    <div :style="{width: '15px',  height: '15px',
                    borderRadius: '8px',  
                    position: 'relative',
                    backgroundColor: activeStep >= 1 ? '#408dff' : '#d7d9da'
                    }">
                    <div style="width: 10px; height: 10px; background-color: #fff;
                    border-radius: 5px; position: absolute; top: 2.5px; left: 2.55px;"></div>    
                </div>
                </template>
            </el-step>
            <el-step title="检查并完成" class="custom-step">
                 <template #icon>
                    <div :style="{width: '15px',  height: '15px',
                    borderRadius: '8px',  
                    position: 'relative',
                    backgroundColor: activeStep >= 2 ? '#408dff' : '#d7d9da'
                    }">
                    <div style="width: 10px; height: 10px; background-color: #fff;
                    border-radius: 5px; position: absolute; top: 2.5px; left: 2.55px;"></div>    
                </div>
                </template>
            </el-step>
        </el-steps>
        </div>
        <!-- 角色信息 -->
         <div  v-show="activeStep === 0" style="width: 800px; height: 230px;background-color: #fff; padding: 20px;
         position: relative; 
         ">
          <text>角色信息</text>
          <div style="position: absolute; top: 70px; left: 180px; ">
            <el-form ref="formRef" :rules="formRules" :model="roleform">
              <el-form-item label="角色名称：" prop="roleName"> 
                <el-input placeholder="请输入角色姓名" v-model="roleform.roleName"  style="width: 450px;"></el-input>
              </el-form-item>
              <el-form-item label="角色描述：" prop="">
                <el-input type="textarea" v-model="roleform.remark" placeholder="请输入角色描述" :resize="'none'"   style="width: 450px;"></el-input>
              </el-form-item>
            </el-form>
          </div>
         </div>
         <!-- 权限信息 -->
          <div v-show="activeStep === 1" style="width: 800px; height: auto; padding: 20px;
          background-color: #fff;
          margin-bottom: 80px;
          " >
            <div style="margin-bottom: 20px;"> <text>权限配置</text></div>
              <div class="tree-wrapper">
                <div v-for="(item,index) in treeList" :key="item.id" class="tree-item"
                :class="{ 'no-bottom-border':  item.title && ['一体杆管理', '系统管理'].includes(item.title) }">
                  <div class="tree-title">{{ item.title }}</div>
                  <el-tree :data="item.children"
                  show-checkbox
                  default-expand-all
                  node-key="id"
                  :props="{label:'title'}"
                  ref="treeRefs"
                  :default-checked-keys="roleform.perms[index]"
                  ></el-tree>
                </div>
              </div>
          </div>
       <!-- 检查并完成 -->
         <div v-show="activeStep === 2" style="width: 800px; margin-bottom: 80px; height:auto; min-height: 100vh; background-color: #fff;" >
            <div style="padding: 20px;"><text>检查并完成</text></div>
            <div>
              <div class="form-item" ><el-text>角色名称：{{ roleform.roleName }}</el-text></div>
              <div class="form-item"><el-text>角色描述：{{ roleform.remark }}</el-text></div>
              <div class="form-item"> <el-text>角色权限：</el-text></div>
              <div class="tree-wrapper">
                <div v-for="item in treeList" :key="item.id" class="tree-item"
                :class="{'no-bottom-border' : item.title && ['一体杆管理','系统管理'].includes(item.title)}">
                <div class="tree-title">{{ item.title }}</div>
                <el-tree :data="item.children"
                show-checkbox
                default-expand-all
                node-key="id"
                :props="{label:'title', disabled:()=> true }"
                ref="disabledTreeRefs"
                ></el-tree>
              </div>
                 </div>
            </div>
         </div>
        </div> 
    </main>
    <footer>
      <div style="background-color: #fff; height: 64px; width: 100vw;
       position: fixed;bottom: 0px; display: flex; justify-content: center;
       align-items: center; z-index: 8; ">
         <el-button v-if="activeStep > 0" @click="prevStep()">上一步</el-button>
         <el-button type="primary" v-if="activeStep < 2 " @click="nextStep()">下一步</el-button>
        <el-button type="primary" v-if="activeStep === 2" @click="addRole()">{{ route.params.id ? '确认修改' :'确认添加' }}</el-button>
      </div>
    </footer>
  </div>
</template>

<script setup lang='ts'>
import { changeRoleAPI, getPermissionAllTreeAPI, getRoleDetailAPI, postAddRole } from '@/apis/system';
import type { RoleDetail, RowChild } from '@/types/system';
import { ElMessage, type FormInstance, type FormRules } from 'element-plus';
import type { TreeInstance } from 'element-plus/lib/components/index.js';
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';

  // 获取表单
  const formRef = ref<FormInstance>()
  // 校验规则
  const formRules = ref<FormRules>({
    roleName:[{required:true,message:'请输入角色名称',trigger:'blur'}]
  })
  // 
  const roleform = ref<RoleDetail>({
    perms:[],
    remark:'',
    roleName:'',
  })

  // 树形组件
  const treeRefs = ref<TreeInstance[]>([])
  // 表单3数据回显
  const disabledTreeRefs = ref<TreeInstance[]>([])
  // 下一步
  const nextStep = async() =>{
    try{

      // 只有在第一步时才进行校验
      if(activeStep.value === 0){
      // 进行表单校验
      await formRef.value?.validate()
       activeStep.value ++ 
      }

      // 在第二步时进行权限是否选中校验
      else if(activeStep.value === 1){
        // 首先初始化空数组
        roleform.value.perms = []
        treeRefs.value.forEach((tree)=>{
          // 获取选中节点的key值
          const arrKeys = tree.getCheckedKeys () as number[];
          console.log('获取选中节点的key值',arrKeys)
          // 追加到分布表单的数组中
          roleform.value.perms.push(arrKeys)
        })  

         // 把二维数组转扁平化 再判断长度
         if(roleform.value.perms.flat().length === 0){
          ElMessage.error('请选择角色的权限')
         }else{
           // 校验没有问题进入表单3
           activeStep.value ++ 
          //  表单3 数据回显
          disabledTreeRefs.value.forEach((tree,index) =>{
            tree.setCheckedKeys(roleform.value.perms[index])
          })
         }
      }
    }catch{

    }

  }
  // 添加路由
  const router = useRouter()
  // 添加角色
  const addRole = async() =>{

    const rowId = Number(route.params.id)
    console.log('rowId：',rowId)
    // 有id就是编辑
      if(rowId){
        const res = await changeRoleAPI({
          roleId: Number(rowId),
          ...roleform.value
        })
        console.log('编辑角色',res)
      }else{
            // 无id就是添加
       const res = await postAddRole(roleform.value)
      console.log('添加角色：',res)
      }

      ElMessage.success(route.params.id ? '编辑成功' : '添加成功')
      router.back()
  } 
  // 上一步
  const prevStep = () =>{
    activeStep.value --
  }

  // 当前激活的步骤
  const activeStep = ref(0)

  // 树形结构图列表
  const treeList = ref<RowChild[]>([])

  // 获取功能权限列表
  const getTreeList = async() =>{
    const res = await getPermissionAllTreeAPI()
    console.log('获取功能权限列表',res)
    treeList.value = res.data   
  }

  getTreeList()

  // 回显角色信息
  // 1.获取角色详情
//   const route = useRoute()
//   const getRoleDetail = async()=>{
//     if(route.params.id){
//       const res = await getRoleDetailAPI(String(route.params.id))
//       const {roleName,remark,perms} = res.data
//       roleform.value = {roleName,remark,perms}
//   }
// }

// 回显角色信息
const route = useRoute()  
const getRoleDetail = async () =>{
  // 如果有id才获取角色详情
  if(route.params.id){
    // 回显数据
      const res = await getRoleDetailAPI(Number(route.params.id))
  const { roleName,remark,perms } = res.data
  roleform.value = {roleName,remark,perms}
  }

}

getRoleDetail()
</script>
<style lang='scss' scoped>

.form-item{
  width: 100%;
  margin-left: 80px;
  margin-bottom: 20px;
}

::v-deep .el-tree {
  // 子节点之间的垂直间距（全局生效）
  .el-tree-node {
    margin-bottom: 8px; // 可根据需求调整，如6px、10px
  }
}
.tree-title{
  background-color: #f5f7fa;
  height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 20px;
}

/* 模块容器：每行内的单个模块 */
.tree-item {
  width: 26%; // 每行 3 个，占 1/3 宽度；如需每行 4 个，改为 25%
  border-right: solid #dcdde0 1px;
  border-bottom: solid #dcdde0 1px;
  padding: 20px 20px; // 左右内边距统一
  &:last-child { // 每行内的最后一个模块，移除右边框
    border-right: none;
  }
  &:nth-child(3){
     border-right: none;
  }
}
.tree-wrapper{
  width: 100%; // 改为100%，填满父容器（800px）
  padding: 20px; // 与外层容器的padding一致，避免多余间距
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
}

.no-bottom-border{
  border-bottom: none;
}

/* 隐藏步骤圆圈内的数字 */
.el-step__icon-inner {
  display: none;
}

/* 去除外层容器的背景和边框，消除白色方块 */
::v-deep .el-step__icon {
  border-radius: 20px;
  width: 18px;
  background-color: #f4f6f8;
}

::v-deep .custom-step {
  // 让 icon 和文字垂直居中对齐
  display: flex;
  align-items: center;
  // 手动调整间距
  .el-step__title {
    margin-left: 10px; 
  }
}

/* 关键：手动绘制竖线，通过容器的伪元素实现 */
::v-deep .el-steps {
  position: relative;
  /* 给竖线预留位置，根据需求调整 */
  padding-left: 0px; 
  z-index: 2;
}

::v-deep .el-steps::before {
  content: '';
  position: absolute;
  left: 11px; /* 和图标圆心对齐，根据图标大小微调 */
  top: 20px;
  height: 120px;
  bottom: 0;
  width: 2px;
  z-index: 1;
  background-color: #d7d9da; /* 连线颜色，可自定义 */
}



</style>